import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';

const AuthContext = createContext(null);

const STORAGE_KEY = 'nexusgo.auth';

function readStoredAuth() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { isAuthenticated: false, token: null, user: null };
    const parsed = JSON.parse(raw);
    return {
      isAuthenticated: !!parsed?.token || !!parsed?.user,
      token: parsed?.token || null,
      user: parsed?.user || null,
    };
  } catch {
    return { isAuthenticated: false, token: null, user: null };
  }
}

export function AuthProvider({ children }) {
  const [isAuthenticated, setIsAuthenticated] = useState(() => readStoredAuth().isAuthenticated);
  const [token, setToken] = useState(() => readStoredAuth().token);
  const [user, setUser] = useState(() => readStoredAuth().user);
  const [authModalVisible, setAuthModalVisible] = useState(false);
  const [authModalMode, setAuthModalMode] = useState('login'); // 'login' | 'register'

  useEffect(() => {
    const payload = JSON.stringify({ token, user });
    localStorage.setItem(STORAGE_KEY, payload);
  }, [token, user]);

  const signIn = (nextToken, nextUser) => {
    setToken(nextToken || null);
    setUser(nextUser || null);
    setIsAuthenticated(!!nextToken || !!nextUser);
    try {
      const payload = JSON.stringify({ token: nextToken || null, user: nextUser || null });
      localStorage.setItem(STORAGE_KEY, payload);
    } catch {}
    try {
      if (nextToken) {
        document.cookie = `Bearer=${encodeURIComponent(nextToken)}; Path=/`;
      }
    } catch {}
  };

  const signOut = () => {
    setToken(null);
    setUser(null);
    setIsAuthenticated(false);
    localStorage.removeItem(STORAGE_KEY);
    try {
      document.cookie = 'Bearer=; Path=/; Max-Age=0';
    } catch {}
  };

  const updateUser = (nextUser) => {
    setUser(nextUser || null);
    setIsAuthenticated(!!token || !!nextUser);
    try {
      const payload = JSON.stringify({ token, user: nextUser || null });
      localStorage.setItem(STORAGE_KEY, payload);
    } catch {}
  };

  const openAuthModal = (mode = 'login') => {
    setAuthModalMode(mode);
    setAuthModalVisible(true);
  };

  const closeAuthModal = () => {
    setAuthModalVisible(false);
  };

  const value = useMemo(() => ({ 
    isAuthenticated, token, user, 
    signIn, signOut, updateUser,
    authModalVisible, authModalMode, openAuthModal, closeAuthModal
  }), [isAuthenticated, token, user, authModalVisible, authModalMode]);

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used within AuthProvider');
  return ctx;
}